package lxs.swift.tool.acc;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class Inlet<I> {
    private final List<Wrapper<I, ?>> wrappers = new ArrayList<>();

    public void in(I in) {
        for (Wrapper<I, ?> wrapper : wrappers) {
            wrapper.port.push(in);
        }
    }

    public <O> void server(Port<I, O> port, Consumer<O> consumer) {
        Wrapper<I, O> wrapper = new Wrapper<>(port, consumer);
        wrappers.add(wrapper);
    }

    public void notice() {
        for (Wrapper<I, ?> wrapper : wrappers) {
            wrapper.notice();
        }
    }

    private static class Wrapper<I, O> {
        final Port<I, O> port;
        final Consumer<O> consumer;

        private Wrapper(Port<I, O> port, Consumer<O> consumer) {
            this.port = port;
            this.consumer = consumer;
        }

        public void notice() {
            O o = port.pull();
            consumer.accept(o);
        }
    }
}
